package com.qf.dao.Impl;

import com.qf.bean.CartBean;
import com.qf.dao.CartDao;
import com.qf.pojo.Cart;

import com.qf.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author yangl
 * @version 1.0
 * @date 2023/4/26 14:34
 */
public class CartDaoImpl implements CartDao {

    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public void insert(Cart cart) {
        //获取连接
        Connection connection = DBUtils.getConnection();

        //sql
        String sql = "insert into t_cart(uid,pid,price,num,created_user," +
                "created_time,modified_user,modified_time,status) values(?,?,?,?,?,?,?,?,?)";

        //调用方法
        try {
            queryRunner.update(connection, sql, cart.getUid(),cart.getPid(),cart.getPrice(),
                    cart.getNum(),cart.getCreated_user(),cart.getCreated_time(),
                    cart.getModified_user(),cart.getModified_time(),cart.getStatus());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<CartBean> findAll(Integer uid) {
        //获取连接
        Connection connection = DBUtils.getConnection();

        //sql
        String sql = "SELECT c.cid,c.num,c.price realPrice,c.modified_time,p.image,p.title " +
                "FROM t_cart c " +
                "INNER JOIN t_product p " +
                "ON c.pid = p.id " +
                "WHERE uid = ? " +
                "ORDER BY modified_time DESC";

        //调用方法
        List<CartBean> cartBeanList = null;

        try {
            cartBeanList = queryRunner.query(connection, sql, new BeanListHandler<>(CartBean.class),uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return cartBeanList;
    }
}
